<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>公司信息编辑</title>
<link rel="stylesheet" href="../../css/ecp.min.css" />
<link rel="stylesheet" href="../../css/picUpload.css" />
<script src="../../js/lib.min.js"></script>
<script src="../../js/requirejsConfigObj.js"></script>
<script src="../../js/requirejs/2.1.17.js"></script>
<script src="../../js/datepicker/4.8.b2/WdatePicker.js"></script>
<script src="../../js/common.min.js"></script>

<style  type="text/css">
    .check_error{color:red;border-color:red;}
    .width130{width:460px;height: 25px;}
    .errText{margin-left:10px;visibility:hidden; }

</style>    
</head>
<body> 
  <div id="showMsg" class="project"></div> 
  <div class="project-dialog"> 
   <form id="formItem" name="formItem" style="width: 100%;"> 
     <div>
     	<input type="hidden" id="approvalFlagHide" value=""/> 
      <table class="form_table" width="95%"> 
       <tbody id="table_tbody">
       <tr>
            <td width="130">
                 <label class="description"> <span class="fn-high">*</span>公司名称</label>
            </td>
            <td width="260" colspan="3">
                <input type="text" class="inputWidth width130" maxlength="200" name="companyNm" id="companyNm"/>                   
            </td>            
       </tr>
       <tr>
            <td>
                 <label class="description"> <span class="fn-high">*</span>公司地址</label>
            </td>
            <td colspan="3">
                <input type="text" class="inputWidth width130" maxlength="200" name="companyAddr" id="companyAddr"/>   
            </td>
        </tr> 
        <tr>
            <td>
                 <label class="description"> <span class="fn-high">*</span>联系电话</label>
            </td>
            <td colspan="3">
                <input type="text" class="inputWidth width130" maxlength="200" name="companyTelnum" id="companyTelnum"/>   
            </td>
        </tr>  
        <tr>
            <td>
                 <label class="description"> 公司照片</label>
            </td>
            <td colspan="3">
                <div class="row cl">
					<input type='hidden' id='filepath'>
                    <div class="uploader-thum-container">
                    	<input type=file id=browsefile style="visibility:hidden;" onchange="imgFileOpt();"/>
						<div id="fileList" class="" style="height:auto;margin-bottom:20px;"></div>
						<div class="normalBtnArea" style="clear: both;">
							<a class="normalBtn BGblue largeBtn" href="javascript:;" id="" style="padding: 12px 20px;" onclick="browsefile.click();">选择图片</a> 
						</div>
                	</div>
                	<p style="margin-top:10px;">照片类型支持：JPEG、PNG、JPG、Gif格式的图片,照片小于2M</p>
				</div>     
            </td>
        </tr>
        <tr>
           <td>
               <label class="description">公司简介</label>
           </td>
           <td colspan="3">
               <textarea type="text" name="companyDesc" id="companyDesc" class="form-textarea"  placeholder="请输入2000字以内" style="width: 700px;height: 130px;" resize:none ;onblur="true" maxlength="500"></textarea>
           </td>
       </tr>
       <tr>
        <td>
            <label class="description"> <span class="fn-high">*</span>公司介绍</label>
        </td>
        <td colspan="3">
            <textarea type="text" name="companyCntt" id="companyCntt" style="width:650px;height:400px;visibility:hidden;"></textarea>
        </td>
       </tr>       
       </tbody> 
      </table> 
      <hr />
     <div class="formBtnArea"> 
      <table width="100%"> 
       <tbody>
        <tr> 
         <td> 
          <div class="normalBtnArea fn-center"> 
           <input type="hidden" id="companyId" name="companyId" value=""/>
           <a class="normalBtn BGblue largeBtn" href="javascript:;" id="J_save" attr_save_type="1" onclick="save()">保存</a> 
           <a href="javascript:;" class="BGblue largeBtn" id="J_cancel" onclick="cancleConfirm()"><span>返回</span></a> 
          </div> 
          </td> 
        </tr> 
       </tbody>
      </table> 
     </div> 
    </div> 
   </form> 
  </div>
 </body>

<script src="../../js/kindeditor/kindeditor.js"></script>
<script src="../../js/self_fun.js"></script>
<script type="text/javascript">
$(function(){
	//qryOpAndRaVal();	
	editor = KindEditor.create('textarea[name="companyCntt"]', {
        allowFileManager: true,
        uploadJson: "../../front/sh/care!uploadPicImg?uid=p002&type=rich",
        items: [
          'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
          'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
          'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
          'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
          'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
          'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
          'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
          'anchor', 'link', 'unlink', '|', 'about'
        ]
      });
	var companyId = getUrlParam("companyId");
	$("#companyId").val(companyId);
	getCompanyDtl(companyId);
});
  
  function getCompanyDtl(companyId){
	  $("#companyNm").val("");
      $("#companyAddr").val("");
      $("#companyTelnum").val("");
      editor.html('');
      $("#companyDesc").val("");
      $("#fileList").html(""); 
      $("#filepath").val('');
 	 var param = {companyId:companyId};   
 	 Util.ajax.postJsonSync('/getCompanyDtlInfo', param, function(json,status){
          var obj = json.bean;
          if(status){
         	 $("#companyNm").val(obj.companyNm);
              $("#companyAddr").val(obj.companyAddr);
              $("#companyTelnum").val(obj.companyTelnum);             
              editor.html(obj.companyCntt)
              $("#companyDesc").val(obj.companyDesc);
              if(!isDataNull(obj.picHeadFile)){
  	            var imgH = "<img src='"+obj.picHeadFile+"' width='200' height='200'/>";
  	            $("#filepath").val(obj.picHeadFile);
  	            $("#fileList").html(imgH);   
  	            setHeight();
              }
          }else{
              Util.dialog.tips("查询失败,请重试");
          }
 	 });
  }

function save(){  
	var companyNm = $("#companyNm").val();
	var companyAddr = $("#companyAddr").val();
	var companyTelnum = $("#companyTelnum").val();
	var companyDesc = $("#companyDesc").val();
	if(isDataNull(companyNm)){
	   	 top.Util.dialog.tips('请填写公司名称！');
	   	 return;
   	} 
	if(isDataNull(companyAddr)){
	   	 top.Util.dialog.tips('请填写公司地址！');
	   	 return;
	}  
	var filePaths = $("#filePaths").val();
	var ntcCnttContent = "";
   	ntcCnttContent = editor.html();
   	if(ntcCnttContent=='' ||ntcCnttContent==null){
    	 top.Util.dialog.tips('请填写公司介绍！');
    	 return;
    }   
   	var companyId = $("#companyId").val();
   	var filepath = $("#filepath").val();
	var param={
		 'companyId' :companyId,
   		 'companyNm' :companyNm,
   		 'companyAddr' :companyAddr,
   	     'companyTelnum':companyTelnum,
   	     'companyCntt':ntcCnttContent,
   	     'companyDesc':companyDesc,
   	     'picHeadFile':filepath
    }   
	Util.ajax.postJsonSync("/updateCompanyInfo",param,function(json,status){
           if(status){
        	   if(json.bean.rtnCd == "00"){        		   
                   window.parent.inint();
                   window.parent.closeIframeDialog();
               }else{              
                   window.parent.setTip("保存失败",top,2000);
               }
           }else{
               var rtnMsg = json.bean.rtnMsg ? json.bean.rtnMsg : "";
               Util.dialog.tips("保存失败,请重试!!"+rtnMsg);
               //showDialogMsg("保存失败,请重试 !!</br>"+rtnMsg);
           }
     }); 
}
	//取消确认弹框
	function cancleConfirm(){
		//window.location.href = "newProjEstabMana.html?";
		window.parent.closeIframeDialog();
	};	
  
    //表单校验
    var validatePoorHouseInfo = $("#formItem").validate({
    	rules:{
    		companyNm:{
        		required:true,
        	},
        	companyTelnum:{
        		required:true,
        	},
        	companyAddr:{
        		required:true,
            }
        },
        messages:{
        	companyNm:{
        		required:"必填",
            },
            companyTelnum:{
            	required:"必填",
            },
            companyAddr:{
            	required:"必填",
            }
        },
        showErrors:function(){
            this.defaultShowErrors();
        }
    });
    jQuery.validator.addMethod("checkNumber",function(value,element) { 
        var regUrl = /^[1-9]\d{0,14}$/;// /^\d{0,15}$/;
        return this.optional(element) || regUrl.test(value);
    }, "请输入正整数");
    
    jQuery.validator.addMethod("checkLittleNumber",function(value,element) { 
    	var regUrl = /^\d{0,10}(\.\d{1,4})?$/;
        return this.optional(element) || regUrl.test(value);
    }, "保留4位小数");
    
    function checkNumberDecimals(num){
    	var regx = /^\d{0,20}(\.\d{1,2})?$/;
    	if(regx.test(num)){
    		return true;
    	}else{
    		return false;
    	}
    }
  	//账号校验  请正确填写银行账号
    function checkAcctNum(num){
    	var regUrl = /^\+?[1-9][0-9]*$/;
   	  	if(regUrl.test(num) && num.length >= 14 && num.length <= 19){
   		  	return true;
   	  	}else{
   		  	return false;
   	  	}
    }
    function checkTotalInvest(num){
    	var regx = /^\d{0,7}(\.\d{1,4})?$/;
    	if(regx.test(num)){
    		return true;
    	}else{
    		return false;
    	}
    }
    function checkTotalNum(num){
    	var regx = /^\d+$/;
    	if(regx.test(num)){
    		return true;
    	}else{
    		return false;
    	}
    } 
 
  //项目备案材料上传初始化方法
  function initWebS1(fileId,pickerId,picPaths){
	  var $ = jQuery,
     $list = $(fileId),
	// 优化retina, 在retina下这个值是2
	      ratio = window.devicePixelRatio || 1,
	
	// 缩略图大小
	      thumbnailWidth = 100 * ratio,
	      thumbnailHeight = 100 * ratio,
	// Web Uploader实例
	 uploader;
	 var familyPicUrls = '';
	 var allPicUrls = '';//包含所有前端页面预览过的图片的地址
	// 初始化Web Uploader
	uploader = WebUploader.create({
	  // 自动上传。
	  auto: true,
	
	  // 图片上传前进行压缩
	  compress: false,
	  duplicate :true,  
	  // swf文件路径
	  swf:  '../../asset/lib/webuploader/Uploader.swf',
	  //server:'../../front/sh/info!fanxianUploadPicImg?uid=s001',
	  server:'../../front/sh/info!fanxianUploadPicImg?uid=s001',
	  // 选择文件的按钮。可选。
	  // 内部根据当前运行是创建，可能是input元素，也可能是flash.
	  pick: {id:pickerId,multiple:true},
	  // 只允许选择文件，可选。
	  accept: {
	      title: 'Images',
	      extensions: 'gif,jpg,jpeg,bmp,png',
	      mimeTypes: 'image/jpg,image/jpeg,image/png,image/bmp,image/gif'
	  },
	   fileVal: "file",
	   fileSingleSizeLimit:3145728
	});
	
	         
	//图片加入队列前,判断图片大小
	uploader.on('beforeFileQueued',function(file){
	    var picUpload = $(fileId).find(".file-item");
	    if(picUpload.length >= 10){
	      Util.dialog.tips("最多只能上传10张照片",top,1000);
	      return false;
	    }  
	    if(file.size > 3145728){
	        Util.dialog.tips("图片大于3M，请重新选择",top,1000);
	    }
	    var injStra = ["script", "mid", "master", "truncate ", "insert ", "select ",
                       "delete ", "update ", "declare", "iframe", "onreadystatechange", "alert", "atestu", "xss",
                       ";","'","\"","<",">","(",")",",","\\","svg","confirm","prompt","onload","onmouseover",
                       "onfocus","onerror","and ","or ","union ","where ","limit ","group ","by ","hex","substr",
                       "\r","\n"];
        var injFileName = file.name.toLowerCase();
        var flag = 1;
        for (var i = 0; i<injStra.length; i++) {
            if (injFileName.indexOf(injStra[i])>=0) {              
                flag =2;
            }
        }
        if(flag == 2){
            Util.dialog.tips("图片名称含有特殊字符，请修改");                
            return false;
        }
	    window.parent.setIframeHeight();
	})
	uploader.on( 'uploadStart', function( file ) {});
	// 当有文件添加进来的时候
	uploader.on( 'fileQueued', function( file ) {  
	  var $li = $(
	          '<div id="' + file.id + '" class="file-item thumbnail">' +
	          '<img>' +
	          '<div class="delpic"><span id=""  style="color: #08c;visibility:hidden;">删除图片</span></div><div class="excelProcess" style="visibility:hidden;"></div></div>'
	  ),
	  $img = $li.find('img');
	  $list.append( $li );    
	  $("J_save").css('visibility','hidden');         
	$(".delpic").find('span').on('click',function(){
	      var _this=$(this);
	      var picId=_this.attr("id");//在图片上传时已修改为图片地址
	      var picUrls = $(picPaths).val();  
	      var regx = new RegExp('\\$?'+picId);
	      var path = picUrls.replace(regx, "");
	      if(path.indexOf('$') === 0){path = path.substring(1);}
	      $(picPaths).val(path);
	      _this.parents(".file-item").remove();
	      window.parent.setIframeHeight();
	});
	// 创建缩略图
	uploader.makeThumb( file, function( error, src ) {
	  if ( error ) {
	      $img.replaceWith('<span>不能预览</span>');
	      return;
	  }   
	  $img.attr( 'src', src );
	}, 60, 60 );
	window.parent.setIframeHeight();
	});
	
	// 文件上传过程中创建进度条实时显示。
	uploader.on( 'uploadProgress', function( file, percentage ) {
	  $('#'+file.id).find('.excelProcess').css('visibility','visible');
	  $('#'+file.id).find('.excelProcess').html('<p class="progress" style="width:'+percentage * 99+'%"></p><span>'+(percentage.toFixed(2)* 99)+'%</span>');
	  window.parent.setIframeHeight();
	});
	// 文件上传成功，给item添加成功class, 用样式标记上传成功。
	uploader.on( 'uploadSuccess', function(file, data) {
	  var picUrl = data.bean.picUrl+"@"+file.name;
	  var imgName = data.bean.fileName;
	  familyPicUrls = $(picPaths).val();
	  familyPicUrls += "$"+picUrl;
	  if(familyPicUrls.indexOf('$') === 0){familyPicUrls = familyPicUrls.substring(1);}
	  $('#' + file.id).find(".delpic span").attr("id", picUrl);
	  $(picPaths).val(familyPicUrls);//最终上传图片
	  $( '#'+file.id ).addClass('upload-state-done');
	  $('#'+file.id).find('.excelProcess').css('visibility','visible');
	  $('#'+file.id).find('.excelProcess').html('上传成功');
	  $('#'+file.id).find(".delpic span").css('visibility','visible');
	 
	  window.parent.setIframeHeight();
	});
	// 文件上传失败，显示上传出错。
	uploader.on( 'uploadError', function( file ) {
	  var $li = $( '#'+file.id ),
	          $error = $li.find('div.error');
	  if ( !$error.length ) {
	      $error = $('<div class="error"></div>').appendTo( $li );
	  }
	  if(uploader.getFiles('queued','progress').length == 0){
		  $("J_save").css('visibility','visible');
	  }
	  $("#"+file.id).remove();
	});
	
	// 完成上传完了，成功或者失败，先删除进度条。
	uploader.on( 'uploadComplete', function( file ) {
	
	});
	
	//解决ie9下上传png无法到后台的问题
	if(navigator.userAgent.indexOf("MSIE")>0 && navigator.userAgent.indexOf("MSIE 9.0")>0){   
	var setHeader = function(object, data, headers) {
	      headers['Access-Control-Allow-Origin'] = '*';
	      headers['Access-Control-Request-Headers'] = 'content-type';
	      headers['Access-Control-Request-Method'] = 'POST';
	  }
	uploader.on('uploadBeforeSend ', setHeader);
	}
  }

  function zTreeOnClick(event, treeId, treeNode) {
	    if(treeNode.regnCode.substring(9) != '000'){
	    	return;
	    }
		Util.ajax.postJsonSync(srvMap.get('queryRegnOptions'),{regnCode:treeNode.regnCode}, function(json, status) {
			if (status) {
				var treeObj = $.fn.zTree.getZTreeObj("J_zTree");
				var newNodes = json.beans;
				newNodes = treeObj.addNodes(treeNode, newNodes);
			}
		});
	
	}
	var setting = {
		view: {
			selectedMulti: true
		},
		check: {
			enable: true,
			chkStyle: "checkbox",
			chkboxType:{ "Y" : "s", "N" : "s" }
		},
		data: {
			simpleData: {
				enable: true,
				idKey: "regnCode",
				pIdKey: "suprRegnCode",
				rootPId: -1
			},
			key: {
				name: "regnNm"
			}
		},
		callback: {
			onClick: zTreeOnClick
		}
	};
  var initTree = function() {
		var regnCode = $("#cntyCode").val();
		Util.ajax.postJson(srvMap.get('queryRegnOptions'),{'regnCode':regnCode}, function(json, status) {
			if (status) {
				$.fn.zTree.init($("#J_zTree"), setting, json.beans);
				var str = $("#projImplAddr").val();
				if(!isDataNull(str)){
					 showZtree(str);
				}
			}
		});
	}
  function showZtree(arr){
	  if(isDataNull(arr)){
		  return;
	  }
	    var treeObj = $.fn.zTree.getZTreeObj("J_zTree"); 
		var nodes=treeObj.getNodes();
		var obj=treeObj.transformToArray(nodes);
		var regnStrTown = arr.split(",").map(function(x){return x.substring(0,9)+"000"});
		var regnStrAdmin = arr.split(",");
		regnStrTown.map(function(x){
			treeObj.setting.callback.onClick(null, treeObj.setting.treeId, 
					treeObj.getNodeByParam("regnCode",x,null));
		});
		regnStrAdmin.map(function(x){
			treeObj.checkNode(treeObj.getNodeByParam("regnCode",x,null))
		});
	}

//校验投资金额
function projInputAmtCheck(){
	  var value = $("#projInputAmt").val();
	  var regUrl = /^[1-9]\d{0,14}(\.\d{1,4})?$/;
    if(!regUrl.test(value)){
  	  $("#projInputAmt").next().show();
    }else{
  	  $("#projInputAmt").next().hide();
    }
}
function imgFileOpt(){
	var reader = new FileReader();
    var AllowImgFileSize = 2100000; //上传图片最大值(单位字节)（ 2 M = 2097152 B ）超过2M上传失败
    var file = $("#browsefile")[0].files[0];
    var imgUrlBase64;
    if (file) {
        //将文件以Data URL形式读入页面  
        imgUrlBase64 = reader.readAsDataURL(file);
        reader.onload = function (e) {
          //var ImgFileSize = reader.result.substring(reader.result.indexOf(",") + 1).length;//截取base64码部分（可选可不选，需要与后台沟通）
          if (AllowImgFileSize != 0 && AllowImgFileSize < reader.result.length) {
        	  top.Util.dialog.tips( '上传失败，请上传不大于2M的图片！');
                return;
            }else{
                //执行上传操作
                html = '<img src="'+reader.result+'" width="200" height="200"/>';
                $("#fileList").html(html);
                $("#filepath").val(reader.result);
                setHeight();
            }
        }
     }         
}
function setHeight(){
    window.parent.setIframeHeight();
}
</script>
</body>
</html>